/**
 * 配置面板属性页签的mixin 文件，
 *
 * 有特殊情况就覆写方法
 */

import Variables from '@/common/variables.js';
import PropertyDirectives from '@/mixin/property-directives.js';
import dataModel from '@/models/panel-config-data.js';
import { generateRules, genRequireRule, genRulesByKey } from '@/utils/rules';
import { $confirm, objHas } from '@/utils/util';
import { getCommonVal } from '@/utils/util-common.js';
import { mapMutations, mapState } from 'vuex';
import rules from './panel-property-base-rules.js';
import BasicMixin from '@/mixin/base-mixin.js';
import EventBus from '@/event-bus/EventBus.js';
import VsFormItem from '@/components/common/vs-form-item/vs-form-item.vue';
import PanelPropertyBottom from '@/components/common/panel-property/panel-property-bottom.vue';

export default {
  mixins: [BasicMixin, PropertyDirectives],
  components: { VsFormItem, PanelPropertyBottom },
  data() {
    return {
      xvueTheme: window._adoPremise.uc.theme,
      xvueLanguage: window._adoPremise.language || 'zh-CN',
      componentName: '',
      activeColorRadio: '#2D8CF0', // 单选框选中时的颜色
      Variables,
      rules,
    };
  },
  computed: {
    ...mapState({
      panelConfigs: state => state.VisualComponentsModule.panelConfigs,
    }),
    panelConfig() {
      const emptyConfig = {
        siteId: '',
        widgetInstanceId: '',
        property: {},
        data: {
          tableData: [],
        },
        events: {},
      };
      return this.panelConfigs[this.widgetInstanceId] || emptyConfig;
    },
    activeColorSwitch() {
      switch (this.xvueTheme) {
        case 'dark':
          return '#0EB4C2';
        default:
          return '#00AAFF';
      }
    },
    inactiveColorSwitch() {
      switch (this.xvueTheme) {
        case 'dark':
          return '#064559';
        default:
          return '#C0CCDA';
      }
    },
    panelsConf() {
      return null; // 防止vue3报错，表格组件兼容
    },
  },
  inject: {
    isChildComponent: {
      default: false,
    },
  },
  watch: {
    'form.componentStyle': {
      handler(componentStyle) {
        if (componentStyle) {
          this.setState({ formComponentStyle: componentStyle });
        }
      },
      immediate: true,
    },
  },
  provide() {
    return {
      propertyWid: this.widgetInstanceId,
    };
  },
  methods: {
    ...mapMutations(['setState']),
    generateRules,
    genRequireRule,
    genRulesByKey,
    componentStyleChanged(val) {
      const keys = Object.keys(this.colorGroup[val][this.componentName]);
      this.form.color = keys[0];
    },
    handleFontSize(val, type) {
      if (type === 'add') {
        this.form[val]++;
      } else {
        this.form[val]--;
      }
    },

    // 根据主题色获取对应
    getValByCompStl(lightVal, darkVal, realVal) {
      const propertyCompStl = this.config.config.property.componentStyle;
      const componentStyle = this.form.componentStyle || propertyCompStl;

      const map = {
        light: lightVal,
        dark: darkVal,
        real: realVal,
      };
      return map[componentStyle];
    },

    // 获取属性值 'echart.grid.left' => 50
    getPropVal(propKey) {
      const arr = propKey.split('.');
      const len = arr.length;
      let { form } = this;
      for (let i = 0; i < len; i++) {
        const key = arr[i];
        if (!objHas(form, key)) {
          return undefined;
        }
        form = form[key];
      }
      return form;
    },

    /*
     * 传入多个属性，第一个属性无值时，取第二个属性值，第二个没值时取第三个...
     * 使用举例：getDfPropVal('echart.grid.left', 'padding.left')
     */
    getDfPropVal(...args) {
      let val;
      for (let i = 0; i < args.length; i++) {
        val = this.getPropVal(args[i]);
        if (typeof val !== 'undefined') {
          break;
        }
      }
      return val;
    },

    getEchartDfVals(map) {
      const vals = {};
      Object.entries(map).map(([i]) => {
        const n = map[i];
        let val;
        if (Array.isArray(n)) {
          val = this.getDfPropVal(i, ...n);
        } else {
          val = this.getDfPropVal(i, n);
        }
        vals[i] = val;
      });
      return vals;
    },

    // 添加标题组件方法
    initDfCssStyleAttrs(defineCss = {}) {
      const dfAttrs = {
        title: {
          color: { light: '#3c3c3c', dark: '#00f7ff', real: '#eee' },
          fontSize: 18,
          fontWeight: 'normal',
          fontFamily: 'unset',
          backgroundColor: { light: '#fff', dark: '#0D263A', real: '#232323' },
          paddingTop: 10,
          paddingLeft: 20,
          textAlign: 'left',
        },
        headerStyle: {
          color: { light: '#3c3c3c', dark: '#00f7ff', real: '#eee' },
          fontSize: 16,
          fontWeight: 'normal',
          fontFamily: 'unset',
          horizontal: 'center',
          vertical: 'middle',
          showStyle: 'noWrap',
          textIconAlign: 'center',
        },
        contentStyle: {
          color: { light: '#3c3c3c', dark: '#00f7ff', real: '#eee' },
          fontSize: 16,
          fontWeight: 'normal',
          fontFamily: 'unset',
          horizontal: 'center',
          vertical: 'middle',
          showStyle: 'noWrap',
        },
        name: {
          fontSize: 12,
          fontWeight: 'normal',
          fontFamily: 'unset',
          textAlign: 'left',
          lineHeight: 24,
          color: { light: '#436a8f', dark: '#b3cbe1', real: '#eee' },
        },
        group: {
          fontSize: 12,
          fontWeight: 'normal',
          fontFamily: 'unset',
          textAlign: 'left',
          lineHeight: 24,
          color: { light: '#436a8f', dark: '#b3cbe1', real: '#eee' },
        },
        value: {
          fontSize: 12,
          fontWeight: 'normal',
          fontFamily: 'unset',
          textAlign: 'left',
          lineHeight: 24,
          color: { light: '#436a8f', dark: '#b3cbe1', real: '#eee' },
        },
        unit: {
          fontSize: 12,
          fontWeight: 'normal',
          fontFamily: 'unset',
          lineHeight: 24,
          color: { light: '#436a8f', dark: '#b3cbe1', real: '#eee' },
        },
        box: {

          // 组件容器
          backgroundColor: { light: '#fff', dark: '#0D263A', real: '#232323' },
        },
        ...defineCss,
      };
      return dfAttrs;
    },
    changeColorVal() {
      // 留空，兼用历史代码
    },
    check() {
      return new Promise(resolve => {
        this.$refs.form.validate((valid, obj) => {
          let limitValid = true;
          if (this.checkLimit) {
            limitValid = this.checkLimit();
          }
          const res = limitValid && valid;
          if (res) {
            resolve(true);
          } else {
            resolve(obj);
          }
        });
      });
    },
    watchCompBgColor(key) {
      let str = 'form.backgroundColor';
      if (key) {
        str = key;
      }
      this.$watch(str, color => {
        const titleCss = this.form.cssStyle && this.form.cssStyle.title;
        if (titleCss) {
          titleCss.backgroundColor = color;
        }
      });
    },

    initTitleColor() {
      const { title } = this.form.cssStyle;
      if (title) {
        title.backgroundColor = this.getValByCompStl('#fff', '#0D263A', '#232323');
        title.color = this.getValByCompStl('#3c3c3c', '#00f7ff', '#eee');
      }
    },

    syncIcon(fromIcon, toIcon) {
      let _fromIcon = fromIcon;
      let _toIcon = toIcon;
      if (_fromIcon && typeof _fromIcon === 'string') {
        _fromIcon = {
          type: 'serverImg',
          'icon_id': _fromIcon,
          'sourceIcon_id': _fromIcon,
          apiType: 'platform',
          boxStyle: {
            width: 32,
            height: 32,
          },
          imgStyle: {
            width: 32,
            height: 32,
          },
        };
      }
      if (_toIcon && typeof _toIcon === 'string') {
        _toIcon = {
          type: 'serverImg',
          'icon_id': _toIcon,
          'sourceIcon_id': _toIcon,
          apiType: 'platform',
          imgStyle: {
            width: 32,
            height: 32,
          },
          boxStyle: {
            width: 32,
            height: 32,
          },
        };
      }

      if (!_fromIcon || !_fromIcon.icon_id) {
        return false;
      }
      if (!_toIcon || !_toIcon.icon_id) {
        return JSON.parse(JSON.stringify(_fromIcon));
      }

      _toIcon = JSON.parse(JSON.stringify(_toIcon));
      _toIcon.boxStyle = { ..._fromIcon.boxStyle };
      _toIcon.imgStyle = { ..._fromIcon.imgStyle };
      return _toIcon;
    },

    // 初始化form.backgroundColor
    initFormBgColor() {
      const { form } = this;
      if (objHas(form, 'backgroundColor') && !form.backgroundColor) {
        form.backgroundColor = getCommonVal('boxBgColor', form.componentStyle);
      }
    },

    // 地图类组件获取最大区域层级api
    getMaxRegionLevel(maxLevel) {
      const method = 'getChartDataxMiner';
      const apiCode = 'getVisualMaxRegionLevel';
      const params = { apiCode, propertyMapping: { level: 'level' } };
      dataModel[method](params)
        .then(result => {
          const key = maxLevel || 'levelNum';
          this.form[key] = result[0].level;
        })
        .catch(() => {
          this.$message.error(this.$demoi18n('view.getMaxRegionLevelErr'));
        });
    },

    getPanelLabelOverflowTooltip() {
      return {
        parentComp: this,
      };
    },
    delTab(tab) {
      $confirm(this.$demoi18n('message.delTabTip'), this.$demoi18n('popup.title.tips'), {
        confirmButtonText: this.$demoi18n('panel.confirm.ok'),
        cancelButtonText: this.$demoi18n('panel.confirm.cancel'),
        type: 'warning',
      }).then(() => {
        let { tabData } = this.form;
        for (let i = 0; i < tabData.length; i++) {
          if (tab === tabData[i]) {
            tabData = tabData.splice(i, 1);
          }
        }
      });
    },
    extStylesSave(extStyles) {
      this.form = {
        ...this.form,
        extStyles,
      };
    },
  },
  created() {
    if (this.config && this.config.componentName) {
      this.componentName = this.config.componentName;
    }

    /*
     * 监听xvue 发出的事件   $adoPremiseEvtBus为xVue 202009 新增的bus，对应的事件改为由  this.$adoPremiseEvtBus发出
     * 位置变化时
     */
    EventBus.$on('xvue-layout-updated-widget', widget => {
      if (!this.widget) {
        return;
      }
      if (widget.i !== this.widget.i) {
        return;
      }

      // 把更新后的x,y,w,h 值等放入config中
      this.form = {
        ...this.form,
        size: {
          width: widget.w,
          height: widget.h,
        },
        position: {
          x: widget.x,
          y: widget.y,
        },
      };
    });

    // 大小变化时
    EventBus.$on('xVue_GridItemResizedEvent', obj => {
      if (!this.widget) {
        return;
      }
      if (obj.i !== this.widget.i) {
        return;
      }

      // 把更新后的w,h 值等放入config中
      this.form = {
        ...this.form,
        size: {
          width: obj.newW,
          height: obj.newH,
        },
      };
    });

    // 父组件驱动子组件改变风格，案例请看进度表
    EventBus.$on('property_componentStyle_change', componentStyle => {
      this.form.componentStyle = componentStyle;
    });
  },
  mounted() {
    // 根据xvue的属性初始化配置面板的 位置大小信息, xVue 初始化的对象和后面更新后的对象不一致，初始有uui,miX,miY,miHeight,miWidth
    if (this.widget) {
      const { uuid, miX, miY, miHeight, miWidth, x, y, w, h } = this.widget;
      this.form = {
        ...this.form,
        size: {
          width: uuid ? miWidth : w,
          height: uuid ? miHeight : h,
        },
        position: {
          x: uuid ? miX : x,
          y: uuid ? miY : y,
        },
      };
    }

    this.initFormBgColor();
    this.watchCompBgColor();
    this.watchCompBgColor('form.cssStyle.grid.backgroundColor');
    this.watchCompBgColor('form.cssStyle.box.backgroundColor');
  },
  unmounted() {
    EventBus.$off('xvue-layout-updated-widget');
    EventBus.$off('xVue_GridItemResizedEvent');
    EventBus.$off('property_componentStyle_change');
    EventBus.$off(`apiDataChanged_${this.widgetInstanceId}`);
  },
};
